const https = require('https');
const http = require('http');
const fs = require('fs');
const path = require('path');
const express = require('express');
const serveIndex = require('serve-index');

const socketIo = require('socket.io');
const log4js = require('log4js');

// 日志配置
log4js.configure({
    appenders: {
        file: {
            type: 'file',
            filename: 'app.log',
            layout: {
                type: 'pattern',
                pattern: '%r %p - %m'
            }
        }
    },
    categories: {
        default: {
            appenders: ['file'],
            level: 'debug'
        }
    }
});

var logger = log4js.getLogger();

const app = express();
app.use(express.static('./public'));
app.use(serveIndex('./public'));

// 使用从 Ubuntu 上生成并复制到 Windows 上的证书和密钥文件
const options = {
    key: fs.readFileSync(path.resolve(__dirname, 'server.key')),
    cert: fs.readFileSync(path.resolve(__dirname, 'server.cert')),
};

// 创建http服务器
var http_server = http.createServer(app);
http_server.listen(8080, () => {
    console.log('HTTP server running on http://localhost:8080');
});

// 创建 HTTPS 服务器
var https_server = https.createServer(options, app);
var io = socketIo(https_server);

io.sockets.on("connection", function(socket) {
    socket.on("join",(room,username) => {
        socket.join(room);
        console.log(`${username} joined room: ${room}`);
        // 获取当前房间用户数
        const roomSize = io.sockets.adapter.rooms.get(room)?.size || 0;

        console.log(`Room ${room} has ${roomSize} users`);

        // 通知房间内除了新用户的所有人
        socket.broadcast.to(room).emit("joined", `${username} has joined the room: ${room}`,socket.id, room);
        // 仅通知新用户本人
        socket.emit("joined", `You have joined the room: ${room}, there are ${roomSize} users in this room`);
    })

    socket.on("leave",(room) => {
        socket.leave(room);
        console.log(`User left room: ${room}`);

        // 广播给该房间其他用户，通知他们用户已经离开
        socket.to(room).emit("message", `A user has left the room: ${room}`);
    })

    socket.on("message",(room,data) => {
        console.log(data)

        // 通知房间内除了新用户的所有人
        socket.to(room).emit("message", data);
        socket.emit("message", data);
    })
});

// 端口复用。 socketIo和https_server共享端口
https_server.listen(8443, () => {
    console.log('HTTPS server running on https://localhost:8443');
});